package com.rjt.qrcode.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Objects;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;

import com.rjt.common.util.StaticMethod;
import com.rjt.qrcode.model.QrCodeModel;
import com.rjt.qrcode.repository.QrCodeRepository;
import com.rjt.qrcode.service.QrCodeService;
import com.rjt.user.service.UserService;

@Service
public class QrCodeServiceImpl implements QrCodeService{
	
	@Autowired
	private QrCodeRepository qrCodeRepository;
	@Autowired
	private UserService userService;
	
	@Override
	public Page<QrCodeModel> getList(HttpServletRequest request) {
		// TODO Auto-generated method stub
		int curPage = StaticMethod.nullObject2int(request.getParameter("page")) <= 0 ? 1 : 
			StaticMethod.nullObject2int(request.getParameter("page"));
		int pageSize = StaticMethod.nullObject2int(request.getParameter("limit")) <= 0 ? 10 : 
			StaticMethod.nullObject2int(request.getParameter("limit"));
		 PageRequest pageRequest = new PageRequest(curPage-1, pageSize,Direction.DESC, "createDate");
		 QrCodeModel qrCodeModel = new QrCodeModel();
		 qrCodeModel.setuId(userService.getuId());
		 Example<QrCodeModel> example = Example.of(qrCodeModel);
		 return qrCodeRepository.findAll(example,pageRequest);
	}
	@Override
	public String delete(List<QrCodeModel> qrCode) {
		// TODO Auto-generated method stub
		String flag="success";
		 try {
			 qrCodeRepository.delete(qrCode);
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("删除失败");
			flag="error";
		}
		 return flag;
	}
	@Override
	public QrCodeModel findQrCode(String id) {
		// TODO Auto-generated method stub
		return qrCodeRepository.findOne(id);
	}
	@Override
	public String add(QrCodeModel qrCode, String method) {
		// TODO Auto-generated method stub
		String flag="success";
		qrCode.setuId(userService.getuId());
		try {
			if(Objects.equals(method, "save")) {
				String id="Qr"+RandomStringUtils.randomAlphanumeric(6);
				qrCode.setId(id);
				qrCode.setCreateDate(new Date());
				qrCodeRepository.save(qrCode);
			}else if(Objects.equals(method, "edit")){
				qrCode.setCreateDate(new Date());
				qrCodeRepository.save(qrCode);
			}
		} catch (Exception e) {
			// TODO: handle exception
			flag="error";
		}
		return flag;
	}

}
